<?php


namespace App\Http\Controllers\Admin;


use App\Models\Goods;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\GoodsBrand;
use App\Models\GoodsCategory;
use App\Models\GoodsCategorySku;
use App\Models\GoodsSku;
use App\Models\GoodsSkuDetail;
use App\Models\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;

class GoodsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //分类
        $categorys = Category::with('allChilds')
            ->where('parent_id',0)
            ->orderBy('sort','desc')
            ->get();
        return view('admin.goods.index',compact('categorys'));
    }


    public function data(Request $request)
    {
        $model = Goods::query();
//        if ($request->get('category_id')){
//            $model = $model->where('category_id',$request->get('category_id'));
//        }
//        if ($request->get('title')){
//            $model = $model->where('title','like','%'.$request->get('title').'%');
//        }
        $res = $model->orderBy('created_at','desc')
            ->paginate($request->get('limit',30))
            ->toArray();

        $category = GoodsCategory::query()->get()->toArray();
        $category = array_column($category,"category_name","id");
        foreach ($res['data'] as $key => $val){
            $first_category_id = $val["first_category_id"];
            $second_category_id = $val["second_category_id"];
            $res['data'][$key]["first_category_name"] = isset($category[$first_category_id]) ? $category[$first_category_id] : "";
            $res['data'][$key]["second_category_name"] = isset($category[$second_category_id]) ? $category[$second_category_id] : "";
        }

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];

        return response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //分类
        $categorys = GoodsCategory::with('allChilds')
            ->where('parent_id',0)
            ->orderBy('sort','desc')
            ->get();

        //标签
        $tags = Tag::get();

        $specs[] = [
            "id" => 1,
            "title" => "颜色",
            "content" => "颜色,body"
        ];
        $specs[] = [
            "id" => 2,
            "title" => "尺寸",
            "content" => "175,180"
        ];
        $first_category_arr = GoodsCategory::with('allChilds')
            ->where('parent_id',0)
            ->orderBy('sort','desc')
            ->get()
            ->toArray();
        $second_category_arr = [];
        $brand_arr = [];

        return view('admin.goods.create',compact('tags','categorys',
            'specs','first_category_arr','second_category_arr','brand_arr'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();

        $goods_sn = goodsSn("g");
        $images = explode(",",$data["images"]);
        if($data["goods_detail_type"] == 1){
            $description =  $data["images"];
        }else{
            $description = $data["content"];
        }
        DB::beginTransaction();
        try {
            $category_info = GoodsCategory::query()
                ->where("id",$data["category_id"])
                ->where("level",2)
                ->first();
            $date = date("Y-m-d H:i:s");
            $goods = [
                "goods_name" => $data["goods_name"],
                "goods_sn" => $goods_sn,
                "main_image" => $images[0],
                "images" => $data["images"],
                "goods_selling" => $data["goods_selling"],
                "first_category_id" => $category_info->parent_id,
                "second_category_id" => $category_info->id,
                "brand_id" => $data["brand_id"],
                "description_type" => $data["goods_detail_type"],
                "description" => $description,
                "status" => $data["status"],
                "hits" => $data["hits"],
                "sold" => 0,
                "price" => $data["price"],
                "stock" => 0,
                "created_at" => $date,
                "updated_at" => $date,
            ];

            $goods_id = Goods::insertGetId($goods);

            $skus = $data["skus"];
            $specs = $data["specs"];
            $specs_value = $data["specs_value"];

            $i = 0;
            foreach ($specs_value as $key => $val){
                $category_sku = GoodsCategorySku::query()->where("id",$specs[$i])->first();
                $goods_sku_data[] = [
                    "goods_id" => $goods_id,
                    "goods_sn" => $goods_sn,
                    "sku_id" => $category_sku->id,
                    "sku_name" => $key,
                    "sku_image" => $category_sku->image,
                    "sku_detail" => implode(",",$val),
                    "status" => 1,
                    "created_at" => $date,
                    "updated_at" => $date,
                ];
                $i++;
            }
            GoodsSku::insert($goods_sku_data);

            foreach ($skus as $key => $val){
                if($key == "status") continue;

                $goods_sku_detail_data[] = [
                    "goods_id" => $goods_id,
                    "goods_sn" => $goods_sn,
                    "goods_sku_ids" => implode(",",$specs),
                    "image" => $val["picture"],
                    "price" => $val["price"],
                    "stock" => $val["stock"],
                    "sold" => 0,
                    "status" => $val["status"],
                    "created_at" => $date,
                    "updated_at" => $date,
                ];
            }
            GoodsSkuDetail::insert($goods_sku_detail_data);
            return redirect(route('admin.goods'))->with(['status'=>'添加完成']);
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect(route('admin.goods'))->withErrors(['status'=>'系统错误']);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $goods = Goods::query()
            ->where("id",$id)
            ->first()
            ->toArray();
        $goods["image_arr"] = explode(",",$goods["images"]);
        //分类
        $categorys = GoodsCategory::with('allChilds')
            ->where('parent_id',0)
            ->orderBy('sort','desc')
            ->get()
            ->toArray();

        $first_category_arr = GoodsCategory::with('allChilds')
            ->where('parent_id',0)
            ->orderBy('sort','desc')
            ->get()
            ->toArray();
        $second_category_arr = GoodsCategory::query()
            ->where("parent_id",$goods["first_category_id"])
            ->orderBy('sort','desc')
            ->get()
            ->toArray();

        $brand_arr = GoodsBrand::query()
            ->where("category_id",$goods["first_category_id"])
            ->orderBy('sort','desc')
            ->get()
            ->toArray();

        //标签
        $tags = Tag::get();

        //sku
        $goods_sku_detail = GoodsSkuDetail::query()
            ->where("goods_id",$goods["id"])
            ->get()
            ->toArray();
        $goods_sku_detail = array_column($goods_sku_detail,null,"goods_sku_val");
        $goods_sku_detail = json_encode($goods_sku_detail);

        $goods_sku = GoodsSku::query()
            ->where("goods_id",$goods["id"])
            ->get()
            ->toArray();

        $goods_sku_id_arr = GoodsSku::query()
            ->where("goods_id",$goods["id"])
            ->pluck("sku_id")
            ->toArray();

        //该分类的sku信息
        $category_sku = GoodsCategorySku::query()
            ->where("category_id",$goods["first_category_id"])
            ->get()
            ->toArray();
        foreach ($category_sku as $key => $val){
            if(in_array($val["id"],$goods_sku_id_arr)){
                $category_sku[$key]["is_used"] = 1;
            }else{
                $category_sku[$key]["is_used"] = 2;
            }

            $sku_val = explode(",",$val["content"]);
            //选中的sku值
            $sku_detail = array_column($goods_sku,"sku_detail");
            $sku_detail = explode(",",implode(",",$sku_detail));
            foreach ($sku_val as $v){
                $is_used = 2;
                if(in_array($v,$sku_detail)){
                    $is_used = 1;
                }
                $category_sku[$key]["sku_val"][] = [
                    "name" => $v,
                    "is_used" => $is_used,
                ];
            }
        }

        return view('admin.goods.edit',compact('tags','categorys'
            ,'goods','first_category_arr','second_category_arr','brand_arr','goods_sku_detail','category_sku'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();

        $images = explode(",",$data["images"]);
        if($data["goods_detail_type"] == 1){
            $description =  $data["images"];
        }else{
            $description = $data["content"];
        }
        DB::beginTransaction();
        try {
            $category_info = GoodsCategory::query()
                ->where("id", $data["second_category_id"])
                ->where("level", 2)
                ->first();
            $date = date("Y-m-d H:i:s");
            $goods = [
                "goods_name" => $data["goods_name"],
                "main_image" => $images[0],
                "images" => $data["images"],
                "goods_selling" => $data["goods_selling"],
                "first_category_id" => $data["first_category_id"],
                "second_category_id" => $data["second_category_id"],
                "brand_id" => $data["brand_id"],
                "description_type" => $data["goods_detail_type"],
                "description" => $description,
                "status" => $data["status"],
                "hits" => $data["hits"],
                "sold" => 0,
                "price" => $data["price"],
                "stock" => 0,
                "updated_at" => $date,
            ];

            $goods_id = Goods::where("id", $id)->update($goods);

            $skus = $data["skus"];
            $specs = $data["specs"];
            $specs_value = $data["specs_value"];

            GoodsSku::where("goods_id", $id)->delete();
            $i = 0;
//            echo "<pre>";
//            var_dump($specs_value);
//            dd($specs);
            foreach ($specs_value as $key => $val) {
                $category_sku = GoodsCategorySku::query()
                    ->where("id", $specs[$i])
                    ->first();
                $goods_sku_data[] = [
                    "goods_id" => $goods_id,
                    "goods_sn" => "",
                    "sku_id" => $category_sku->id,
                    "sku_name" => $key,
                    "sku_image" => $category_sku->image,
                    "sku_detail" => implode(",", $val),
                    "status" => 1,
                    "created_at" => $date,
                    "updated_at" => $date,
                ];
                $i++;
            }
            GoodsSku::insert($goods_sku_data);

            GoodsSkuDetail::where("goods_id", $id)->deleteAll();
            foreach ($skus as $key => $val) {
                if ($key == "status") continue;

                $goods_sku_detail_data[] = [
                    "goods_id" => $goods_id,
                    "goods_sn" => $goods_sn,
                    "goods_sku_ids" => implode(",", $specs),
                    "image" => $val["picture"],
                    "price" => $val["price"],
                    "stock" => $val["stock"],
                    "sold" => 0,
                    "status" => $val["status"],
                    "created_at" => $date,
                    "updated_at" => $date,
                ];
            }
            GoodsSkuDetail::insert($goods_sku_detail_data);
            return redirect(route('admin.goods'))->with(['status'=>'修改完成']);
        } catch (\Exception $e) {
            DB::rollBack();
            dd($e);
            //return redirect(route('admin.goods'))->withErrors(['status'=>'系统错误']);
        }
    }

}
